package com.internet;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * UDP协议的网络编程
 */
public class UDPTest {

    //发送端
    @Test
    public void sender() throws IOException {

        DatagramSocket socket = new DatagramSocket();



        String str = "我是UDP方式发送的导弹";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);

        socket.send(packet);

        socket.close();

    }
    //接收端
    @Test
    public void receiver() throws IOException {

        DatagramSocket socket = new DatagramSocket(9090);

        byte[] buffer = new byte[100];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);

        socket.receive(packet);

        System.out.println(new String(packet.getData(),0,packet.getLength()));

        socket.close();
    }


    //接收端
    @Test
    public void receiver2() throws IOException {

        //如果是接收端，这个的构造函数需要添加端口号
        DatagramSocket socket = new DatagramSocket(9090);

        byte[] buffer = new byte[100];

        DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);

        //准备接收指定端口的数据包
        socket.receive(datagramPacket);

        socket.close();

    }


    //发送端
    @Test
    public void sender2() throws IOException {

        //发送端不需要在这里指明端口号
        DatagramSocket socket = new DatagramSocket();

        String str = "发送UDP数据";

        byte[] bytes = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        //这里需要指明端口号，发送端服务器的地址，以及将需要发送出去的信息包好
        DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length, inet, 9090);

        //发送
        socket.send(datagramPacket);

        socket.close();
    }



}
